<?php
set_time_limit(0);
$root=preg_replace('/cron$/', '', dirname(__FILE__));

require_once($root."inc.config.php");

require_once($root."initialize.php");

if(($db_msg=cron_initialize()) !== true){

	print_r("Connection error");

}else{ 

	$db=$vars["db"];
	
	$month = date("m");
	
	$dist = array();
	$cdate = date('Y-m-d H:i:s');
	$bonus_date = date('Y-m', mktime(0, 0, 0,$month-1, date("d"), date("Y")));
	$month_date = date('t',mktime(0, 0, 0, $month-1, date("d"), date("Y")));

	$r=mysql_query("select * from gg_users where status='normal' and pool_share>0 and date_format(cdate, '%Y-%m')<='".$bonus_date."'");
	while($user = mysql_fetch_assoc($r))
	{
		$dist[$user['id']]['w']=0;
		$dist[$user['id']]['pool_share']=$user['pool_share'];
		$total_share += $user['pool_share'];
	}
	
	$unit_pool_bonus=mysql_result(mysql_query("select value from gg_settings where param='monthly_mp'"), 0) or 0;;
	//first deduct, first 6 months.
	//if no maintain no bonus for current month, and bonus amount send to 9996 and payout for share, 2.5% card fees for share also
	if($unit_pool_bonus>0){
		
		foreach ($dist as $distid=>$value) {
			if($value['pool_share']>0){
				$pool_bonus = $unit_pool_bonus*$value['pool_share'];
				$balance=mysql_result(mysql_query("select mwallet from gg_users where id=".$distid), 0) or 0;
						
				$sql = "INSERT INTO gg_member_comm SET uid=".$distid.",from_uid=".$distid.",type='w',amount=".$pool_bonus.",volume_type=".$unit_pool_bonus.",percent=".$value['pool_share'].",bonus_date='".$bonus_date."-".$month_date."',cdate='".$cdate."'";
				mysql_query($sql);
				
				$sql = "INSERT INTO gg_member_comm_sum SET uid=".$distid.",w=".$pool_bonus.",bonus_date='".$bonus_date."-".$month_date."',cdate='".$cdate."'";
				mysql_query($sql);
						
				$balance+=$pool_bonus;
				mysql_query("update gg_users set mwallet=".$balance." where id=".$distid);
						
				$sql = "INSERT INTO gg_member_mwallet_record SET aid=1,uid=".$distid.",type='credit',amount=".$pool_bonus.",bal=".$balance.",descr='".$bonus_date.": ".$value['pool_share']." shares * ".$unit_pool_bonus."',cdate='".$cdate."'";
				mysql_query($sql);				
			}
		}
		
		mysql_query("update gg_member_comm set status='confirmed' where bonus_date='".$bonus_date."-".$month_date."'");
	}
	
	print_r("finish");
}
?>